# Maintainer: ZUO Zhihua <zuo.zhihua@qq.com>

_realname=lfortran
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.52.0
pkgrel=1
pkgdesc="Modern open-source (BSD licensed) interactive Fortran compiler built on top of LLVM (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/lfortran/lfortran"
msys2_references=(
  'aur: lfortran'
)
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-clang"
         #"${MINGW_PACKAGE_PREFIX}-mlir"
         "${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-zstd")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-llvm"
             "${MINGW_PACKAGE_PREFIX}-fmt"
             "${MINGW_PACKAGE_PREFIX}-rapidjson")
source=("${url}/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('51fb60960cce602bf439ee3949e9e52fc8feb0b14794263f2654e692387f23a2')

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    _extra_config+=("-DWITH_UNWIND=ON" "-DWITH_LIBUNWIND=ON")
  fi

  LLVM_DIR="${MINGW_PREFIX}/opt/llvm-15/lib/cmake/llvm" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      -DWITH_LSP=ON \
      -DWITH_FMT=ON \
      -DWITH_JSON=ON \
      -DWITH_LLVM=ON \
      -DWITH_MLIR=OFF \
      -DWITH_ZLIB=OFF \
      -DWITH_ZSTD=OFF \
      ../${_realname}-${pkgver}

  "${MINGW_PREFIX}"/bin/cmake.exe --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  "${MINGW_PREFIX}"/bin/cmake.exe --build . --target test
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install .

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
